package com.nulldev.util.web.flexibleKit.flexRenderer.paths.subgens;

import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.graphics.renderIt.api.renderItGraphicsInterface;
import com.nulldev.util.graphics.renderIt.api.core.RITFont;
import com.nulldev.util.graphics.renderIt.api.envcaps.renderItOperations;
import com.nulldev.util.graphics.renderIt.renderer.global.rColors;
import com.nulldev.util.graphics.renderIt.util.renderItUtils;
import com.nulldev.util.graphics.renderIt.util.renderPosition;
import com.nulldev.util.gui.fontAPI.FontManager;
import com.nulldev.util.web.flexibleKit.flexRenderer.FlexEnvironment;
import com.nulldev.util.web.flexibleKit.flexRenderer.paths.PathGenerator;
import com.nulldev.util.web.flexibleKit.flexRenderer.styling.fonts.flexFontManager;
import com.nulldev.util.web.flexibleKit.general.RenderOperation;
import com.nulldev.util.web.flexibleKit.global.GlobalRendererSettings;
import com.nulldev.util.web.flexibleKit.jfvParse.Node;

public class LinkGenerator implements PathGenerator {

	@Override
	public RenderOperation generate(final Node n, final PathGenerationFlags... flags) {
		return new RenderOperation() {

			private RITFont font;

			@Override
			public renderPosition doRender(final renderItGraphicsInterface i, final renderPosition rp, final FlexEnvironment imageCache) {
				final int fontSize = GlobalRendererSettings.SCALE_TEXT_AUTOMATICALLY ? i.viewport_getWidth() / 32 : flexFontManager.getFontSize("strong");
				final String txt = n.getTextContent();
				if (font == null)
					font = i.awt_make_font(FontManager.getFontSetAsAWT(fontSize));
				final int inc = i.text_scalable(txt, rp.getX(), rp.getY(), rp.getX(), font, rColors.blue);
				// FIXME: Use provided extension functions to underline correctly again.
				final int txt_width;
				if (i.supportsOperations(renderItOperations.RIT_AWT_text_width))
					txt_width = i.awt_textWidth(txt);
				else if (i.supportsOperations(renderItOperations.RIT_SWING_text_width))
					txt_width = i.swing_textWidth(txt);
				else
					txt_width = renderItUtils.guessTextWidth(fontSize, txt);
				i.bd_fillRect(rp.getX(), rp.getY() + fontSize + 2, txt_width, 1, rColors.blue);
				rp.addX(txt_width + imageCache.defaultOffset);
				if (!ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE))
					rp.addY(inc);
				return rp;
			}

			@Override
			public Node operationFor() {
				return n;
			}

			@Override
			public boolean keepInline() {
				return ArrayUtils.contains(flags, PathGenerationFlags.RENDER_INLINE);
			}
		};
	}

}
